//
//  SWBookChooseViewController.swift
//  ChildStory
//
//  Created by linhan on 2017/1/11.
//  Copyright © 2017年 Aiya. All rights reserved.
//

import Foundation
import UIKit
class SWBookChooseViewController: SWBaseViewController,UITableViewDataSource,UITableViewDelegate
{
    var chooseCallback:((Int)->Void)?
    
    private var _index:Int = -1
    private var _books:[SWBook] = []
    
    lazy private var _tableView:UITableView = UITableView()
    
    init(books:[SWBook], index:Int = -1) {
        super.init(nibName: nil, bundle: nil)
        _books = books
        _index = index
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    private func setup()
    {
        _tableView.frame = view.bounds
        _tableView.tableFooterView = UIView()
        _tableView.dataSource = self
        _tableView.delegate = self
        _tableView.backgroundColor = UIColor(hex: 0xeceeef)
        _tableView.rowHeight = 44
        //_tableView.separatorColor = ThemeStyle.TableViewSeparatorColor
        view.addSubview(_tableView)
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let Identifier:String = "SWBookChooseCell"
        var cell:UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: Identifier) as? SWBookChooseCell
        if cell == nil
        {
            cell = SWBookChooseCell(style: .default, reuseIdentifier: Identifier, cellWidth: view.width)
        }
        cell?.accessoryType = _index == indexPath.row ? .checkmark : .none
        (cell as? SWBookChooseCell)?.book = _books.valueAt(indexPath.row)
        return cell ?? UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return _books.count
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        tableView.deselectRow(at: indexPath, animated: true)
        chooseCallback?(indexPath.row)
        navigationController?.popViewController(animated: true)
    }
    
    
}
